﻿using Plexi.Tools;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEngine;

namespace Plexi
{
	internal static class KspTools
	{
		private const float _kerbinCellWidth = 0.02f, _slopeHoriDiff = 0.0002f, _slopeThreshold = 3f;
		private static double _elevLon, _elevLat, _offset;

		internal static float GetCellWidthForBody(CelestialBody body)
		{
			return (float)(_kerbinCellWidth / (body.Radius / FlightGlobals.Bodies[1].Radius));//_kerbinCellWidth;//(float)((body.Radius / FlightGlobals.Bodies[1].Radius) * _kerbinCellWidth);
		}

		internal static int GetSeedForCell(CelestialBody body, int cx, int cy)
		{
			return body.flightGlobalsIndex + MathTools.CantorPairing(cx + 360, cy + 360);
		}

		/// <summary>
		/// Tiny bit of code from SCANSat:
		/// https://github.com/S-C-A-N/SCANsat/blob/master/SCANdata.cs#L73-L81
		/// Copyright (c) 2013 damny <df.ksp@erinye.com>
		///	Copyright (c) 2014 David Grandy <david.grandy@gmail.com>
		///	Copyright (c) 2014 technogeeky <technogeeky@gmail.com>
		///	text to include in distribution:
		///	https://github.com/S-C-A-N/SCANsat/blob/master/LICENSE.txt
		/// </summary>
		public static double GetElevation(CelestialBody body, double lat, double lon)
		{
			_elevLon = Mathf.Deg2Rad * lon;
			_elevLat = Mathf.Deg2Rad * lat;
			return body.pqsController.GetSurfaceHeight(new Vector3d(Math.Cos(_elevLat) * Math.Cos(_elevLon), Math.Sin(_elevLat), Math.Cos(_elevLat) * Math.Sin(_elevLon))) - body.pqsController.radius;
		}

		/// <summary>True if the slope around the immediate vicinity of lat,lon is too much to place a movable rock on.</summary>
		/// <param name="elev">The elevation at lat,lon</param>
		public static bool IsTooSloped(CelestialBody body, double lat, double lon, double elev, float cellWidth)
		{
			_offset = cellWidth * 0.05f;
			return Math.Abs(GetElevation(body, lat + _offset, lon + _offset) - elev) >= _slopeThreshold ||
				Math.Abs(GetElevation(body, lat - _offset, lon + _offset) - elev) >= _slopeThreshold;
		}
	}
}
